package com.solotiger.geographic.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout;
import com.solotiger.geographic.R;
import com.solotiger.geographic.biz.BaseSubscriber;
import com.solotiger.geographic.biz.api.NetWorkApi;
import com.solotiger.geographic.biz.model.Album;
import com.solotiger.geographic.biz.model.AlbumResult;
import com.solotiger.geographic.common.AppEngine;
import com.solotiger.geographic.ui.adapter.AlbumAdapter;
import com.solotiger.geographic.ui.base.BaseActivity;
import com.solotiger.geographic.util.SystemUtil;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends BaseActivity implements AdapterView.OnItemClickListener {

    private static final int PERMISSION_REQ_ID_WRITE_EXTERNAL_STORAGE = 3;

    @BindView(R.id.listView)
    ListView mListView;

    @BindView(R.id.refreshLayout)
    TwinklingRefreshLayout mRefreshLayout;

    private AlbumAdapter albumAdapter;

    //总个数
    private int total;
    //当前页
    private int page;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("每日精选");
        //申请权限
        if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, PERMISSION_REQ_ID_WRITE_EXTERNAL_STORAGE)) {
            init();
        }

    }

    /**
     * 初始化
     */
    private void init() {
        AppEngine.ME.init();
        page = 1;
        initListView();
        initRefreshView();

        setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, TestActivity.class);
                SystemUtil.startActivity(mContext, intent);
            }
        });
    }

    private void initListView() {
        albumAdapter = new AlbumAdapter(mContext);
        mListView.setAdapter(albumAdapter);
        mListView.setOnItemClickListener(this);
    }

    /**
     * RefreshView
     */
    private void initRefreshView() {
        ProgressLayout dotView = new ProgressLayout(mContext);
        dotView.setColorSchemeResources(R.color.colorAccent);
        mRefreshLayout.setHeaderView(dotView);
        mRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                //刷新
                loadDatas(false);
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadmoreCanceled();
                //加载更多
                loadDatas(true);
            }
        });

        mRefreshLayout.startRefresh();
    }

    /**
     * 加载数据
     *
     * @param loadMore true 加载更多  false 刷新
     */
    private void loadDatas(final boolean loadMore) {
        if (!loadMore) {
            albumAdapter.clearData();
            page = 1;
        } else {
            //没有更多数据
            if (albumAdapter.getCount() >= total) {
                showMessage("未找到更多数据");
                return;
            }
        }
        NetWorkApi.getAlbums(page)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<AlbumResult>() {
                    @Override
                    public void onNext(AlbumResult albumResult) {
                        total = albumResult.getTotal();
//                        showMessage("加载成功");
                        if (loadMore) {
                            mRefreshLayout.finishLoadmore();
                        } else {
                            mRefreshLayout.finishRefreshing();
                        }
                        if (albumResult != null) {
                            page++;
                            albumAdapter.notifyDataSetChanged(albumResult.getAlbum());
                        }
                    }

                    @Override
                    protected void _onError(Throwable e) {
                        showMessage("加载数据失败");
                        if (loadMore) {
                            mRefreshLayout.finishLoadmore();
                        } else {
                            mRefreshLayout.finishRefreshing();
                        }
                    }
                });
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Album album = albumAdapter.getItem(position);
        Intent intent = new Intent(mContext, PictureActivity.class);
        intent.putExtra(PictureActivity.A_ID, album.getId());
        intent.putExtra(PictureActivity.A_TITLE, album.getTitle());
        SystemUtil.startActivity(mContext, intent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_setting, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.menu_setting: {
                Intent intent = new Intent(mContext, SettingActivity.class);
                SystemUtil.startActivity(mContext, intent);
                break;
            }
        }
        return true;
    }

    public boolean checkSelfPermission(String permission, int requestCode) {
        if (ContextCompat.checkSelfPermission(this,
                permission)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{permission},
                    requestCode);
            return false;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String permissions[], @NonNull int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQ_ID_WRITE_EXTERNAL_STORAGE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    init();
                } else {
                    finish();
                }
                break;
            }
        }
    }
}
